package Chapter22;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class CountOccurrenceOfWords {
    public static void main(String[] args) {
        // Set text in a string
        String text = "Good morning. Hava a good class. " + "Hava a good visit, Hava fun!";

        // Create a TreeMap to hold words as key and count as value
        TreeMap<String, Integer> map = new TreeMap<>();

        String[] words = text.split("[ \n\t\r.,;:!?(){]");
        for (int i = 0; i < words.length; i++) {
            String key = words[i].toLowerCase();

            if (key.length() > 0) {
                if (map.get(key) == null) {
                    map.put(key, 1);
                } else {
                    int value = map.get(key).intValue();
                    value++;
                    map.put(key, value);
                }
            }
        }

        // Set all entries int a set
        Set<Map.Entry<String, Integer>> entrySet = map.entrySet();

        // Get key and value from each entry
        System.out.println();
        for (Map.Entry<String, Integer> entry : entrySet) {
            System.out.println(entry.getValue() + "\t" + entry.getKey());
        }
    }
}
